/**
 * Created by jiexin on 2017/12/9.
 */
layui.use(['laydate', 'layer', 'laytpl', 'table', 'form', 'element', 'jqprint', 'migrate'], function() {
    var laydate = layui.laydate; //日期
    var layer = layui.layer; //弹层
    var table = layui.table; //表格
    var $ = layui.jquery;
    var form = layui.form;
    var laytpl = layui.laytpl;
    var element = layui.element; //元素操作
    var jqprint= layui.jqprint;
    var migrate=layui.migrate;

    var ah_a = document.getElementById("history_dome");
    var ah_h = ah_a.offsetHeight - 70;

    Date.prototype.format = function(fmt) { //author: meizz
        var o = {
                "M+" : this.getMonth()+1,                 //月份
                "d+" : this.getDate(),                    //日
                "h+" : this.getHours(),                   //小时
                "m+" : this.getMinutes(),                 //分
                "s+" : this.getSeconds(),                 //秒
                "q+" : Math.floor((this.getMonth()+3)/3),   //季度
                "S"  : this.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt))
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        for(var k in o)
            if(new RegExp("("+ k +")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));

        return fmt;
    };


    $("#searcho").on('click', function () {
        var post_data_name =  {'name':$('#in_o').val(),"type":1};
        history_sel(post_data_name)
    });

    laydate.render({
        id:'datetimes'
        ,elem: '#datetimes'
        ,range: true
        // ,format: 'yyyy-MM-dd'
        ,max: new Date().format("yyyy-MM-dd")
        ,min: '2017-01-01'
        ,done: function(value, date, endDate){
            // console.log(value); //得到日期生成的值，如：2017-08-18
            // console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
            // console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
            var datetime = value;
            if (datetime !== ""){
                var post_date_data = {'date':datetime,"type":0};
                history_sel(post_date_data)
            }
        }
    });

    function history_sel(p_data) {
        $.ajax({
            url: '/audit-date/'
            ,dataType: 'json'
            ,type: 'POST'
            ,data: p_data
            ,success: function (a_r_data) {
                console.log(a_r_data);
                if (a_r_data["status"] === 0){
                    historytable.reload({
                        data:a_r_data["return_his_data"]
                    })
                }else {
                    layer.msg("查询失败")
                }
            }
        })
    }

    console.log(history_data);
    var table_format_h = [[
        {field: 'originator', align: 'center', title: '发起人', width: '15%'}
         , {field: 'item_list', align: 'center', title: '模块列表', width: '40%'}
         , {field: 'describe', align: 'center', title: '当前角色', width: '15%'}
         , {field: 'createDate', align: 'center', title: '发起时间', width: '15%'}
         , {field: 'completeDate', align: 'center', title: '完成时间', width: '15%'}
         , {fixed: 'right',width: '20%', align: 'center',  title: '操作', toolbar: '#historyDemo', templet: '#historyDemo'}
    ]];

    $('#audit_history').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        createtableh(etaleid,tableid,history_data,table_format_h,ah_h);
        historytool(toolid,tableid);
    });

    var historytable;
    function createtableh(etaleid,tableid,datas,table_format,h_height) {
        historytable = table.render({
            elem: etaleid,
            id: tableid,
            limit: 10,
            height:h_height,
            page: true,
            data: datas,
            cols: table_format
        });
    }

    var hkey_root,hkey_path,hkey_key;
    hkey_root="HKEY_CURRENT_USER";
    hkey_path="\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";

    // 设置页眉页脚为空
    function PageSetup_Null() {
        try{
             var RegWsh = new ActiveXObject("WScript.Shell") ;
             hkey_key="header" ;
             RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"") ;
             hkey_key="footer" ;
             RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"") ;
        }
        catch(e){}
    }

    // 设置页眉页脚为默认值
    function PageSetup_Default() {
        try{
             var RegWsh = new ActiveXObject("WScript.Shell") ;
             hkey_key="header" ;
             RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"&w&b页码，&p/&P") ;
             hkey_key="footer" ;
             RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"&u&b&d") ;
         }
        catch(e){}
    }

    function PrintPage() {
        PageSetup_Null() ;
        window.print() ;
        PageSetup_Default() ;
    }


    var deal_with_id;
    function historytool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            // var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);
            if (layEvent === "preview"){
                createprint(data);
                $("#display").jqprint({ operaSupport: true });
            }else if (layEvent === "rejected_c"){
                console.log(data);
                // var name = data["dismiss_role"];
                // var reason = data["dismiss_reason"];
                var hname = data["rule_name"];
                var dismiss = data["dismiss_reason"];
                checkrejected(hname,dismiss)
            }
        })
    }

    function createprint(cdata) {

        $.each(cdata, function (k,v) {
            var k_id = "#";
            var n_v;
            if (k === "item_list"){
                n_v = JSON.parse(v);
                var n_d = "";
                for (var i = 0; i<n_v.length; i++){
                    if (i === n_v.length -1){
                        n_d += n_v[i]
                    }else {
                        n_d += n_v[i] + ','
                    }
                }
                k_id += k;
                $(k_id).text(n_d)
            }else if (k === "item_describe"){
                 n_v = JSON.parse(v);
                 generateList(n_v)
            }else{
                k_id += k;
                $(k_id).text(v)
            }
        })
    }


    var getTpl = demot.innerHTML;
    function generateList(gdata) {
        $(".tr-demot").remove();
        for (var i = 0 ; i < gdata.length; i++){
            var idname = gdata[i]["title"];
            var addjson = {title: idname, ionename: idname+"__1", itwoname: idname+"__2", tonename: idname+"__3", ttwoname: idname+"__4"};
            laytpl(getTpl).render(addjson, function(html){
                // view.innerHTML += html;
                $("#item_page").after(html)
            });
            $.each(gdata[i], function (k,v) {
                if (k !== "title"){
                    $("#"+k).text(v)
                }
            })
        }
    }


    function checkrejected(cname, creason) {
        var end_context='<form id="checkrejected" name="checkrejected" class="layui-form layui-form-pane" style="color:#000"><div class="layui-form-item"><label class="layui-form-label">驳回角色</label><div class="layui-input-inline"><input id="whyname" type="text" name="whyname" placeholder="请输入" autocomplete="off" class="layui-input" disabled></div></div><div class="layui-form-item layui-form-text"><label class="layui-form-label">驳回原因</label><div class="layui-input-block"><textarea id="whydata" name="whydata" placeholder="请输入内容" class="layui-textarea" style="resize:none" disabled></textarea></div></div></form>';
        layer.msg(
            content=end_context,
            {
            time: 200000,
            area: ['380px', '280px'],
            //200s后自动关闭
            btn: ['取消'],
            success: function (layero) {
                $("#whyname").val(cname);
                $("#whydata").val(creason);
                var btn = layero.find('.layui-layer-btn');
                btn.css('text-align', 'center');
            }
        });
    }



});